package com.findsing.jetty.websocket.server.endpoint;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;

import com.findsing.jetty.websocket.model.HandShake;
import com.findsing.jetty.websocket.model.Message;
import com.findsing.jetty.websocket.util.Coder;
import com.findsing.jetty.websocket.util.Coder.MessageDecoder;
import com.findsing.jetty.websocket.util.Coder.MessageEncoder;

@ServerEndpoint(value = "/broadcast", encoders = { MessageEncoder.class }, decoders = { MessageDecoder.class })
public class BroadcastServerEndpoint extends BaseEndpoint{
	private static final Logger logger = Logger.getLogger(BroadcastServerEndpoint.class.getName());
	
	HttpSession httpSession;
	
	@OnOpen
	public void onOpen(final Session session, EndpointConfig config) {
		super.onOpen(session, config);
	}

	@OnClose
	public void onClose(final Session session) {
		super.onClose(session);
	}

	@OnMessage
	public void onMessage(final Message message, final Session client) throws IOException, EncodeException {
		for (final Session session : sessions) {
			if(message.getMessageName().equals("Greeting"))
			{
				HandShake handShake = Coder.toObject(message.getMessageBody());
				httpSession = this.getHttpSession(handShake.getJsessionId());
			}
			
			logger.info(String.format("[ver:%d.%d][%s] %s - %s",
					Message.getMajorVersion(),
					Message.getMinalVersion(),
					(null == httpSession)?"UNKOWN":httpSession.getAttribute("userName"),
					message.getMessageName(), 
					message.getMessageBody()));
			
			session.getBasicRemote().sendObject(message);
		}
	}
	
	@OnError
	public void onError(final Throwable t, final Session session)
	{
		;
	}
}
